package com.qf.springcloud.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限校验过滤器
 */
@Component
public class AuthenticationFilter extends ZuulFilter {

    @Override   // 指定过滤器类型
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override   // 过滤器执行顺序
    public int filterOrder() {
        return FilterConstants.SEND_FORWARD_FILTER_ORDER + 100;
    }

    @Override   // 过滤器的开关
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("Authentication过滤器执行了!!");
        // 要求客户端在请求时,必须携带一个参数 token=123,如果没穿,没有权限,不让你继续执行
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        String token = request.getParameter("token");
        if(!"123".equalsIgnoreCase(token)){
            // 用户未登录
            requestContext.setSendZuulResponse(false);   // 代表请求在这终止
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());  // 响应状态码
         }
        return null;
    }






}
